package com.bailong.nanny.controller;

import com.bailong.nanny.base.BaseServlet;
import com.bailong.nanny.d.UserDao;
import com.bailong.nanny.dao.impl.UserDaoImpl;
import com.bailong.nanny.entity.Page;
import com.bailong.nanny.entity.User;
import com.bailong.nanny.service.AddUserService;
import com.bailong.nanny.service.UserService;
import com.bailong.nanny.service.impl.AddUserServiceImpl;
import com.bailong.nanny.service.impl.UserServiceImpl;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import sun.rmi.runtime.Log;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

@WebServlet(name = "/user.do",urlPatterns = "/user.do")
public class UserServlet extends BaseServlet {
    public static String userid = "";
    public static final String UPLOAD_DIR = "D:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\upload\\";
    public void selectAllUser(HttpServletRequest req, HttpServletResponse resp)throws IOException{
        try {
            resp.setContentType("text/html;charset=UTF-8");
            UserService service = new UserServiceImpl();
            List<User> list = service.selectAllUser();
            req.setAttribute("users",list);
            req.getRequestDispatcher("/user.do?m=selectUserLimit").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        if(ServletFileUpload.isMultipartContent(req)) {
            //创建上传对象
            ServletFileUpload servletFileUpload = new ServletFileUpload();
            //限制上传文件总大小
            servletFileUpload.setSizeMax(30 * 1024 * 1024);
            //限制单个文件上传大小
            servletFileUpload.setFileSizeMax(10 * 1024 * 1024);
            try {
                User user = new User();
                //获得文件项目迭代器
                FileItemIterator itemIterator = servletFileUpload.getItemIterator(req);
                //循环迭代表单项目
                while (itemIterator.hasNext()) {
                    //获得表单项
                    FileItemStream item = itemIterator.next();
                    if (item.isFormField()) {
                        String value = Streams.asString(item.openStream(), "UTF-8");
                        switch (item.getFieldName()) {
                            case "username":
                                user.setUsername(value);
                                break;
                            case "realname":
                                user.setRealName(value);
                                break;
                            case "address":
                                user.setAddress(value);
                                break;
                            case "tel":
                                user.setTel(value);
                                break;
                        }
                    } else {
                        File file = new File(UPLOAD_DIR+ UUID.randomUUID()+".jpg");
                        OutputStream outputStream = new FileOutputStream(file);
                        switch (item.getFieldName()) {
                            case "pic":
                                user.setPic(file.getName());
                                break;

                        }
                        Streams.copy(item.openStream(), outputStream, true);
                    }

                }
                AddUserService addUserService = new AddUserServiceImpl();
                int i = addUserService.AddUserDao(user);
                if (i != 0) {
                    req.getSession().setAttribute("error", "添加成功");
                    req.setAttribute("sss","success");
                    System.out.println("添加成功");
                    resp.sendRedirect("/user.do?m=selectAllUser");

                } else {
                    System.out.println("添加失败");
                    req.setAttribute("sss","fail");
                    req.getSession().setAttribute("error", "添加失败");
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("判断异常");
        }
    }
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int id = Integer.parseInt(req.getParameter("user_id"));
        UserService userService = new UserServiceImpl();
        int temp = userService.deleteUser(id);
        if(temp!=0){
            System.out.println("删除成功");
            req.getRequestDispatcher("/user.do?m=selectAllUser").forward(req,resp);
        }else {
            System.out.println("删除失败");
        }

    }
    private void selectUserLimit(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        String pageNo = req.getParameter("pageNo");
        int no = 1;
        if(pageNo!=null){
            no = Integer.parseInt(pageNo);
        }
        UserService userService = new UserServiceImpl();
        Page<User> page= userService.selectUsersPage(no);
        System.out.println("用户名" + page.getList().get(0).getUsername());

        req.setAttribute("page",page);
        try {
            req.getRequestDispatcher("/users.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        }
//        resp.sendRedirect("/users.jsp");
    }
    private void selectUserById(HttpServletRequest req, HttpServletResponse resp){
        UserService userService = new UserServiceImpl();
        String id = req.getParameter("id");
        User user = userService.selectUserById(Integer.parseInt(id));
        System.out.println("查到了：" + user);
        try {
            String json = new Gson().toJson(user);
            resp.getWriter().println(json);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private void updateUser(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charset=UTF-8");
        String id = req.getParameter("id");
        if(ServletFileUpload.isMultipartContent(req)) {
            //创建上传对象
            ServletFileUpload servletFileUpload = new ServletFileUpload();
            //限制上传文件总大小
            servletFileUpload.setSizeMax(30 * 1024 * 1024);
            //限制单个文件上传大小
            servletFileUpload.setFileSizeMax(10 * 1024 * 1024);
            try {
                User user = new User();
                //获得文件项目迭代器
                FileItemIterator itemIterator = servletFileUpload.getItemIterator(req);
                //循环迭代表单项目
                while (itemIterator.hasNext()) {
                    //获得表单项
                    FileItemStream item = itemIterator.next();
                    if (item.isFormField()) {
                        String value = Streams.asString(item.openStream(), "UTF-8");
                        switch (item.getFieldName()) {
                            case "username":
                                user.setUsername(value);
                                break;
                            case "realname":
                                user.setRealName(value);
                                break;
                            case "address":
                                user.setAddress(value);
                                break;
                            case "tel":
                                user.setTel(value);
                                break;
                        }
                    } else {
                        File file = new File(UPLOAD_DIR+ UUID.randomUUID()+".jpg");
                        OutputStream outputStream = new FileOutputStream(file);
                        switch (item.getFieldName()) {
                            case "pic":
                                user.setPic(file.getName());
                                break;

                        }
                        Streams.copy(item.openStream(), outputStream, true);
                    }

                }
                user.setUser_id(Integer.parseInt(id));
                UserService userService = new UserServiceImpl();
                System.out.println(user);
                int i = userService.updateUser(user);
                if (i==0) {
                    System.out.println("修改失败");
                    req.setAttribute("sss","fail");
                    req.getSession().setAttribute("error", "修改失败");
                } else {
                    req.getSession().setAttribute("error", "修改成功");
                    req.setAttribute("sss","success");
                    System.out.println("修改成功");
                    resp.sendRedirect("/user.do?m=selectAllUser");
                }
            } catch (FileUploadException | IOException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("判断异常");
        }
    }
}
